package com.jeffpalm.floto.isight;

import java.awt.Container;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.DateFormat;
import java.util.Date;

import javax.swing.JOptionPane;

import com.jeffpalm.floto.isight.app.ErrorHandler;
import com.jeffpalm.floto.isight.app.Log;
import com.jeffpalm.floto.isight.app.MessageShower;
import com.jeffpalm.floto.isight.osx.MacScreenCapture;
import com.jeffpalm.floto.isight.osx.QuicktimeCapture;
import com.jeffpalm.floto.isight.util.ClientHttpRequest;
import com.jeffpalm.floto.isight.util.Util;

public final class Depot implements URLRequester, ErrorHandler, MessageShower, Log, Capture.Factory {

  private static Depot instance;

  public static Depot getInstance() {
    if (instance == null) {
      instance = new Depot();
    }
    return instance;
  }

  private Depot() {}

  /**
   * Shows a message.
   */
  public void showMessage(String msg) {
    JOptionPane.showMessageDialog(null, msg);
  }

  /**
   * Shows an error.
   */
  public void showError(String msg) {
    JOptionPane.showMessageDialog(null, msg, "Error", JOptionPane.ERROR_MESSAGE);
  }

  /**
   * Shows a message and returns the response.
   * 
   * @return the response.
   */
  public String showInput(String msg) {
    return JOptionPane.showInputDialog(null, msg);
  }

  public void handle(Throwable err) {
    handle(err, null);
  }

  public void handle(Throwable err, String msg) {
    if (err != null) err.printStackTrace();
    if (msg != null) System.err.println(msg);
  }

  public void note(Object who, Object msg) {
    String smallDate = DateFormat.getTimeInstance().format(new Date());
    System.err.println("[" + who + " " + smallDate + "] " + msg);
  }

  public int showConfirm(Container p, String msg) {
    return JOptionPane.showConfirmDialog(null, p, msg, JOptionPane.OK_CANCEL_OPTION);
  }

  public WebcamCapture newWebcamCapture() {
    try {
      return new QuicktimeCapture();
    } catch (Throwable _) {}
    return null;
  }

  public ScreenShotCapture newScreenShotCapture() {
    try {
      return new MacScreenCapture();
    } catch (Throwable _) {}
    return null;
  }

  public String postRequest(String url, Object[] args) throws MalformedURLException, IOException {
    return Util.readAndClose(ClientHttpRequest.post(new URL(url), args));
  }


}
